using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Security.Cryptography;

namespace Havivi.PropertyBagSettings.Features.PropertyBagSettings
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("e27a5014-a70f-4969-8239-a1efdcf27b15")]
    public class PropertyBagSettingsEventReceiver : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            TripleDESCryptoServiceProvider tDESalg = new TripleDESCryptoServiceProvider();

            byte[] key = tDESalg.Key;
            string sKey = string.Empty;
            byte[] iv = tDESalg.IV;
            string sIV = string.Empty;
            SPFarm farm;
            farm = SPFarm.Local;
            for (int i = 1; i < 25; i++)
            {
                sKey += key[i - 1].ToString();
                if (i != 24)
                {
                    sKey += "-";
                }
            }

            if (!farm.Properties.ContainsKey("pbs_secret_key"))
            {
                farm.Properties.Add("pbs_secret_key", sKey);
                farm.Update();
            }
            for (int i = 1; i < 9; i++)
            {
                sIV += iv[i - 1].ToString();
                if (i != 8)
                {
                    sIV += "-";
                }

            }
            if (!farm.Properties.ContainsKey("pbs_initialization_vector"))
            {
                farm.Properties.Add("pbs_initialization_vector", sIV);
                farm.Update();
            }


        }




        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            //Do nothing if the Property Bag Settings feature is deactivated 

        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
        }
    }
}
